import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View, Button, Image,
} from 'react-native';
import DeviceRn from '../Tools/device';
import { connect } from 'react-redux';
import * as Action from './count.time.action';
class CountTime extends Component{
    constructor(props) {
        super(props);
        this.props = props;
        this.state={};
        this.num=0;
    }
    componentWillReceiveProps(nextProps){
       nextProps.status=='update'?this.timeDown(nextProps.data.countdown):"";
    }
    componentWillUnmount(){
        clearInterval(this.time);
    }
    //时间倒计时
    timeDown(timer) {
        clearInterval(this.time);
        this.time = setInterval(() => {
            if (timer > 0) {
                this.num = 0;
                this.index == 2 ? '' : this.index = 1;
                this.CountTime = DeviceRn().timeFormat(timer);
                this.setState({date:this.CountTime});
                timer--;
            } else {
                this.index == 1 ? this.CountTime = "." : '';
                this.index = 2;
                this.operatTime();
            }
        }, 1000);
    }

    //操作函数
    operatTime() {
        let str = this.CountTime || '.';
        this.time != undefined ? '' : this.time = null;
        if (str.length > 4) {
            this.CountTime = '.';
            this.setState({date:this.CountTime});
            this.num++;
            this.num>4?(this.props.dispatch(Action.timeEndRequest(this.props.data)),this.num=2):"";
        } else {
            this.CountTime = str + '.';
            this.setState({date:this.CountTime});
        }
    }

    render() {
        return(
        <View>
            <Text style={this.props.style}>{this.state.date}</Text>
        </View>
        );
    }
}
function select(store) {
    return {
        status: store.countTime.status,
        data: store.countTime.data
    }
}
export default connect(select)(CountTime);